package com.liwen.web.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Aspect
@Component
public class MainAspect {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //定义一个公用方法
    @Pointcut("execution(public * com.liwen.web.controller.MainController.*(..))")
    public void MainAspect() {

    }

    @Before("MainAspect()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        log.info("url={}", request.getRequestURI());
        //method
        log.info("method={}", request.getMethod());
        //ip
        log.info("ip={}", request.getRemoteAddr());
        //method
        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //param
        log.info("args={}", joinPoint.getArgs());
    }

    @After("MainAspect()")
    public void doAfter() {
        log.info("doAfter**************************************");
    }

    @Around("MainAspect()")
    public void interceptor(ProceedingJoinPoint point) {
        log.info("进入around方法");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        Object result = null;
        //当前拦截的类和方法：
        Class clazz = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        String method = signature.getMethod().getName();
        try {
            result = point.proceed(point.getArgs());
            log.info("开始执行后续操作：" + result);
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
        try {
            String s ="";
            if(!"testHttp".equals(method)){
                s = JSON.toJSONString(result);
            }

            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
            writer.close();
        }catch(Exception e) {
            log.error("返回值异常",e);
        }
    }
}
